package com.qidian.mes.qc.excel.listener;/**
 * ClassName:listener
 * Package:com.qidian.mes.qc.excel
 **/

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.qidian.mes.pojo.Flaw;
import com.qidian.mes.qc.service.FlawService;
import com.qidian.mes.util.pojo.QdResult;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author ppc
 * @Conpany study
 * @Description:
 * @Time 2024/4/12 19:06
 *
 **/
public class FlawExcelParseListener implements ReadListener<Flaw> {
    //不能被Spring管理，所以属性只能通过构造方法或者setter方法手动注入
    private FlawService flawService;

    public FlawExcelParseListener(FlawService flawService) {
        this.flawService = flawService;
    }

    private static final int BATCH_COUNT = 5;
    //缓存读取得数据
    private List<Flaw> flaws = new ArrayList<>();
    private int count = 0;
    public int getCount(){
        return count;
    }

    /**
     * 每次 读取一行数据都会调用此方法
     * @param data
     * @param analysisContext
     */

    @Override
    public void invoke(Flaw data, AnalysisContext analysisContext) {
        if(flaws.size() >= BATCH_COUNT ){
            QdResult<Integer> result = flawService.saveFlaws(flaws);
           count += result.getData();

           //清空
            flaws.clear();
            return;
        }
        flaws.add(data);
    }

    /**
     * 整个文件读取结束后
     * @param analysisContext
     */

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if(flaws.size() > 0) {
            QdResult<Integer> result = flawService.saveFlaws(flaws);
            count += result.getData();
        }
    }
}
